package main

import (
	"bytes"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
)

// 通过MarGo实现的daemon方式样子
func main() {
	addr := []string{"xxxxx"}
	d := flag.Bool("d", false, "Whether or not to launch in the background(like a daemon)")
	if *d {
		cmd := exec.Command(os.Args[0], "-close-fds", "-addr", *addr, "-call", *call)
		serr, err := cmd.StderrPipe()
		if err != nil {
			log.Fatalln(err)
		}
		err = cmd.Start()
		if err != nil {
			log.Fatalln(err)
		}
		s, err := ioutil.ReadAll(serr)
		s = bytes.TrimSpace(s)
		if bytes.HasPrefix(s, []byte("addr:")) {
			fmt.Println(string(s))
			cmd.Process.Release()
		} else {
			log.Printf("unexpected response from MarGo: `%s` errors: `%v`\n", s, err)
			cmd.Process.Kill()
		}

	}
}
